import { useState, useCallback } from 'react';
import { useGlobalStore } from '~/stores/index';
import { errorHandler } from '~/utils/errorHandler';

interface RequestOptions<T> {
  onSuccess?: (data: T) => void;
  onError?: (error: Error) => void;
  manual?: boolean;
  initialData?: T;
}

export function useRequest<T = any>(
  service: (...args: any[]) => Promise<T>,
  options: RequestOptions<T> = {}
) {
  const [data, setData] = useState<T | undefined>(options.initialData);
  const [loading, setLoading] = useState(!options.manual);
  const [error, setError] = useState<Error>();
  const setGlobalLoading = useGlobalStore(state => state.setLoading);

  const run = useCallback(async (...args: any[]) => {
    setLoading(true);
    setGlobalLoading(true);
    try {
      const result = await service(...args);
      setData(result);
      options.onSuccess?.(result);
      return result;
    } catch (e: any) {
      const err = new Error(e.message);
      setError(err);
      options.onError?.(err);
      errorHandler(e);
      throw err;
    } finally {
      setLoading(false);
      setGlobalLoading(false);
    }
  }, [service, options, setGlobalLoading]);

  return { data, loading, error, run };
}